package com.hx.mypetstore.ui.myInfo;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.hx.mypetstore.Bean.InfoBean;
import com.hx.mypetstore.R;
import com.hx.mypetstore.constant.SPConstants;
import com.hx.mypetstore.network.HttpURL;
import com.hx.mypetstore.util.SPUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MyInfoActivity extends AppCompatActivity implements View.OnClickListener{

    private EditText ed_sex;

    private EditText ed_age;

    private EditText ed_habit;

    private ImageView im_back;

    private Button bt_quxiao;

    private Button bt_yes;

    private Context mContext;
    private String TAG = "Info";

    /**
     * 用于从网络初始化UI的handler
     */
    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //定义一个弹出层dialog
            AlertDialog alert = new AlertDialog.Builder(mContext).create();

            switch (msg.what) {
                case 0:
                    //网络请求成功，但是返回状态为失败
                    Toast.makeText(mContext, msg.obj == null ? "请求处理失败！获取商品数据失败！"
                            : msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    //网络请求信息数据成功
                    ed_sex.setText(SPUtil.get(mContext,SPConstants.INFOSEX,"").toString());
                    ed_age.setText(SPUtil.get(mContext,SPConstants.INFOAGE,"").toString());
                    ed_habit.setText(SPUtil.get(mContext,SPConstants.INFOHABITE,"").toString());
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_info);
        mContext = getApplicationContext();
        init();
        initDate();
    }

    private void initDate() {
        String url = HttpURL.GETINFO;
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("userid", SPUtil.get(mContext,SPConstants.KEY_LOCAL_USER,"").toString())
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    Message message = Message.obtain();
                    if(!jsonObject.getBoolean("success"))
                        message.what = 0;
                    else{
                        Gson gson = new Gson();
                        InfoBean infoBean = gson.fromJson(jsonObject.getString("data"), InfoBean.class);
                        SPUtil.put(mContext,SPConstants.INFOSEX,infoBean.getSex());
                        SPUtil.put(mContext,SPConstants.INFOAGE,infoBean.getAge());
                        SPUtil.put(mContext,SPConstants.INFOHABITE,infoBean.getHabit());
                        message.what =  1;
                        //   Log.e(TAG, "onResponse: "+SPUtil.get(mcontext,SPConstants.KEY_VIP,"") );
                    }
                    uiHandler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void init() {

        ed_sex = findViewById(R.id.tv_info_sex);
        ed_age = findViewById(R.id.tv_info_age);
        ed_habit = findViewById(R.id.tv_info_habit);
        im_back = findViewById(R.id.info_back);
        bt_quxiao = findViewById(R.id.info_btn_quxaio);
        bt_yes = findViewById(R.id.info_btn_yes);
        im_back =findViewById(R.id.info_back);
        im_back.setOnClickListener(this);
        bt_quxiao.setOnClickListener(this);
        bt_yes.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.info_back:
                finish();
                break;
            case R.id.info_btn_quxaio:
                Message message = Message.obtain();
                message.what =  1;
                uiHandler.sendMessage(message);
                break;
            case R.id.info_btn_yes:
                updataDate();
                break;
        }
    }

    private void updataDate() {
        String url = HttpURL.UPDATEINFO;
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("userid", SPUtil.get(mContext,SPConstants.KEY_LOCAL_USER,"").toString())
                .add("age",ed_age.getText().toString())
                .add("sex",ed_sex.getText().toString())
                .add("habit",ed_habit.getText().toString())
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    Message message = Message.obtain();
                    if(!jsonObject.getBoolean("success"))
                        message.what = 0;
                    else{
                        Gson gson = new Gson();
                        InfoBean infoBean = gson.fromJson(jsonObject.getString("data"), InfoBean.class);
                        SPUtil.put(mContext,SPConstants.INFOSEX,infoBean.getSex());
                        SPUtil.put(mContext,SPConstants.INFOAGE,infoBean.getAge());
                        SPUtil.put(mContext,SPConstants.INFOHABITE,infoBean.getHabit());
                        message.what =  1;
                        //   Log.e(TAG, "onResponse: "+SPUtil.get(mcontext,SPConstants.KEY_VIP,"") );
                    }
                    uiHandler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}